package com.lwl.handler;

import com.alibaba.fastjson.JSON;
import com.lwl.common.RpcRequest;
import com.lwl.util.SpringContextUtil;
import com.lwl.utils.Constants;
import com.lwl.zk.ZookeeperUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * 自定义业务处理器
 */
@Component
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    //当读取到客户端发来的数据时,该方法会被自动调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        System.out.println("接收到客户端信息：" + JSON.toJSON(msg).toString());
        //将读到的msg对象，强转成RpcRequest对象
        RpcRequest rpcRequest = (RpcRequest) msg;

        //加载class文件ss
        Class<?> aClass = Class.forName(rpcRequest.getClassName());
        //通过class获取服务器spring容器中service类的实例化bean对象
        Object serviceBean = SpringContextUtil.getBean(aClass);

        //region 使用自带jdk完成动态代理

        Method method = aClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        method.invoke(serviceBean,rpcRequest.getParameters());


        //服务器写入数据，将结果返回给客户端
        ctx.writeAndFlush("success");

        String path = ctx.channel().localAddress().toString();
        writeLastTime(path);
    }

    //服务端写入最后响应时间
    public void writeLastTime(String path){
        String childPath = Constants.ZK_BASEPATH+path;
        ZookeeperUtils.writeData(childPath,new Date().getTime());
    }
}
